﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

public class ChanceSkill : MonoBehaviour {
	public int orderIndex;
	public SpriteRenderer skillIconMat;
	public BoardPerson person;
	public static Dictionary<string, Sprite> spriteDic = new Dictionary<string, Sprite>();
	public bool isAchieveInGame;

	// Use this for initialization
	void Start () {
		if(!isAchieveInGame)
		{
			int skillId = int.Parse(HudManager.Instance.tempSkillListByGameOrder[HudManager.Instance.charOrderSidDic[orderIndex]].ToString());
			SetSkill (skillId);
		}
	}

	public void SetSkill(int skillId)
	{
		Debug.LogError("chance skill set skillID - " + skillId);
		CSkillData skillData = CSkillDataManager.Instance.FindSkillData(skillId);
		if(skillData!=null)
		{
			if( !spriteDic.ContainsKey(skillData.icon_name) )
			{
				Sprite sprite = LoadSkillIcon(skillData.icon_name);
				if( sprite != null )
				{
					skillIconMat.sprite = sprite;
				}
			}
			else
			{
				Sprite sprite = spriteDic[skillData.icon_name];
				if( sprite != null )
					skillIconMat.sprite = sprite;
			}
		}
	}

	public static Sprite LoadSkillIcon(string name)
	{
		Sprite sprite = Resources.Load<Sprite>("skillIcon/"+name);
		if( sprite != null )
		{
			Debug.LogError("first LoadSkillIcon resoruce load ");
			spriteDic.Add ( name , sprite);
		}
		return sprite;
	}

	void MoveToCharPanel()
	{
		glog.debug("moveto charpanel");
		GetComponent<Animator>().enabled = false;
		//if(isAchieveInGame)
		{
			Invoke("OnMoveFinished",0.5f);
			return;
		}
		transform.parent.parent = UIManager.Instance.centerAnchor.transform;
		transform.parent.gameObject.layer = UIManager.Instance.centerAnchor.layer;
		HudManager.Instance.ChangeLayer( gameObject, UIManager.Instance.centerAnchor.layer);
		transform.parent.localPosition = CardManager.Instance.FindScrPosCenter(person.transform.position);
		transform.parent.localRotation = Quaternion.identity;
		transform.parent.localScale = Vector3.one;
		transform.parent.parent = HudManager.Instance.GetCharacterPanel(person.SID).m_Char.transform;
		float scaleFlipX=1;
		if( HudManager.Instance.GetCharPanel(person.SID).transform.localScale.x < 0)
			scaleFlipX=-1;
		LeanTween.moveLocal( transform.parent.gameObject, Vector3.zero, 0.5f).setOnComplete(OnMoveFinished);
		LeanTween.scale( transform.parent.gameObject, new Vector3(scaleFlipX*0.5f,0.5f,0.5f), 0.5f);
		/*
		TweenPosition twPosition = gameObject.AddComponent<TweenPosition>();
		twPosition.from = transform.localPosition;
		twPosition.to = HudManager.Instance.charPanel[orderIndex].transform.parent.localPosition;
		twPosition.duration = .5f;
		twPosition.delay = 0f;
		EventDelegate.Set(twPosition.onFinished, OnMoveFinished);
		twPosition.PlayForward();*/
	}

	void OnMoveFinished()
	{
		transform.parent.gameObject.SetActive(false);
		glog.debug("onMoveFinished");
		Destroy(transform.parent.gameObject, 1.0f);
		ObjectPool.Recycle(this);
	}
}
